package com.boot.security.server.service.impl;

import com.boot.security.server.agency.model.domain.AgencyRecord;
import com.boot.security.server.agency.service.AgencyRecordService;
import com.boot.security.server.dao.MailDao;
import com.boot.security.server.user.mapper.SysUserMapper;
import com.boot.security.server.model.Mail;
import com.boot.security.server.user.model.SysUser;
import com.boot.security.server.service.MOverseeQuestionService;
import com.boot.security.server.service.MailService;
import com.boot.security.server.service.SendMailSevice;
import com.boot.security.server.utils.UserUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 */
@Service
public class MailServiceImpl implements MailService {
    private static final Logger log = LoggerFactory.getLogger("adminLogger");
    @Autowired
    private SendMailSevice sendMailSevice;
    @Autowired
    private MailDao mailDao;
    @Autowired
    private MOverseeQuestionService questionService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private AgencyRecordService agencyService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save (Mail mail, List<String> toUser) {
        mail.setUserId(UserUtil.getLoginUser().getId());
        mailDao.save(mail);
        toUser.forEach(u -> {
            int status = 1;
            int sendTimes = 0;
            try {
                sendMailSevice.sendMail(u, mail.getSubject(), mail.getContent());
            } catch (Exception e) {
                log.error("发送邮件失败", e);
                status = 0;
                sendTimes++;
            }
            mailDao.saveToUser(mail.getId(), u, status, sendTimes);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void sendMail () {
        log.info(new Date() + ": 定时任务开始！");
        List<AgencyRecord> agencyRecords = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(agencyRecords)) {
            agencyRecords.forEach(agency -> {
                SysUser user = userMapper.selectByPrimaryKey(agency.getToUserId());
                ul(agency, user);
                em(agency, user);
                agencyService.update(agency);
            });
        }
    }

    private void ul (AgencyRecord agency, SysUser user) {
        log.info(new Date() + ": U聊开始！");
        if (StringUtils.isNotEmpty(user.getUl())) {
            int status = 1;
            try {
                // TODO U聊通知
            } catch (Exception e) {
                log.error("发送邮件失败", e);
                status = 0;
            }
            agency.setEm(status);
        } else {
            log.info("请" + user.getUsername() + "配置U聊账号！！！");
        }
    }

    private void em (AgencyRecord agency, SysUser user) {
        log.info(new Date() + ": 邮件开始！");
        Mail mail = new Mail();
        mail.setSubject("代办消息");
        mail.setContent("您还有代办没有处理，请及时处理！地址：" + agency.getRelationUrl());
        mail.setUserId(Long.valueOf(agency.getRelationId()));
        mailDao.save(mail);
        if (StringUtils.isNotEmpty(user.getEmail())) {
            int status = 1;
            int sendTimes = 0;
            try {
                sendMailSevice.sendMail(user.getEmail(), mail.getSubject(), mail.getContent());
            } catch (Exception e) {
                log.error("发送邮件失败", e);
                status = 0;
                sendTimes++;
            }
            mailDao.saveToUser(mail.getId(), user.getEmail(), status, sendTimes);
            agency.setEm(status);
        } else {
            log.info("请" + user.getUsername() + "配置邮箱！！！");
        }
    }

    @Override
    public void inquirySending () {
        List<Mail> mails = mailDao.inquirySending();
        if (CollectionUtils.isNotEmpty(mails)) {
            mails.forEach(mail -> {
                int status = 1;
                int sendTimes = mail.getSendTimes();
                try {
                    sendMailSevice.sendMail(mail.getToUsers(), mail.getSubject(), mail.getContent());
                } catch (Exception e) {
                    log.error("发送邮件失败", e);
                    status = 0;
                    sendTimes++;
                }
                mailDao.saveToUser(mail.getId(), mail.getToUsers(), status, sendTimes);
            });
        }
    }
}
